#include	"ComputerTank.h"
#include	<Math/Vector.h>
#include	<cmath>
#include	<windows.h>
#include	<gl/gl.h>
#include	<gl/glu.h>

ComputerTank::ComputerTank()
	:	ITank()
	,	m_player(0)
	,	m_lastFacingChange(0.0f)
{
}

#pragma warning( disable: 4127 )

void ComputerTank::update(double delay)
{
	if((m_pos == Vector2i(-1, -1)) && (m_life > 0))
	{
		m_pos = m_map->getEnemyPos();
	}
	else if(m_life <= 0)
	{
		return;
	}
	// space
	m_lastShot += float(delay);
	m_lastFacingChange += delay;
	if(isPlayerAhead() && (m_lastShot > (ITank::SHOT_SPEED * 2)))
	{
		shoot();
	}
	if((-EPSILON <= m_distance) && (m_distance <= EPSILON))
	{
		if(!checkWall(m_facing))
		{
			m_distance = float(m_speed * delay);				
		}
		else if(m_lastShot >= ITank::SHOT_SPEED)
		{
			shoot();
		}
		else
		{
			setNewDirection(getNewDirection());
		}
	}
	else
	{
		m_distance += float(m_speed * delay);
	}
	if(m_distance >= (1.0f - EPSILON))
	{
		switch(m_facing)
		{
		case left:
			m_pos[0] -= 1;
			break;
		case right:
			m_pos[0] += 1;
			break;
		case up:
			m_pos[1] -= 1;
			break;
		case down:
			m_pos[1] += 1;
			break;
		}
		m_distance = 0.0f;
		setNewDirection(((std::rand() % 5) > 1) ? m_facing : getNewDirection());
	}
}

bool ComputerTank::isPlayer() const
{
	return false;
}

void ComputerTank::setPlayer(ITank * player)
{
	m_player = player;
}

bool ComputerTank::isPlayerAhead() const
{
	const Vector2i & pos = m_player->getPos();
	switch(m_facing)
	{
	case left:
		return (m_pos[1] == pos[1]) && (m_pos[0] > pos[0]);
	case right:
		return (m_pos[1] == pos[1]) && (m_pos[0] < pos[0]);
	case up:
		return (m_pos[0] == pos[0]) && (m_pos[1] > pos[1]);
	case down:
		return (m_pos[0] == pos[0]) && (m_pos[1] < pos[1]);
	}
	return false;
}

Facing ComputerTank::getNewDirection() const
{
	int choice = std::rand() % 4;
	switch(choice)
	{
	case 0:
		return left;
	case 1:
		return right;
	case 2:
		return up;
	case 3:
		return down;
	}
	return up;
}

void ComputerTank::setNewDirection(Facing facing)
{
	if((m_facing != facing) && (m_lastFacingChange > 0.5))
	{
		m_lastFacingChange = 0.0;
		m_facing = facing;
	}
}

